package com.anji.sp.controller;

import com.anji.sp.enums.UploadFileTypeEnum;
import com.anji.sp.model.ResponseModel;
import com.anji.sp.model.vo.SpUploadVO;
import com.anji.sp.service.SpUploadService;
import com.anji.sp.util.APPVersionCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 公告管理
 *
 * @author zhudaijie
 * @date 2020/06/24
 */
@RestController
@RequestMapping("/upload")
@Api(tags = "上传功能")
public class SpFileUploadController {

    @Autowired
    private SpUploadService spUploadService;

    /**
     * 文件上传
     * @param spUploadVO
     * @return
     */

    /**
     * 文件上传
     *
     * @param fileUpload 上传的文件
     * @param appId      appId
     * @return
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "/uploadFile/v1")
    public ResponseModel uploadFile(@RequestParam("fileUpload") MultipartFile fileUpload,
                                    @RequestParam("appId") String appId,
                                    @RequestParam("type") Long type) {

        if (Objects.isNull(type)) {
            type = UploadFileTypeEnum.APK.getLongCode();
        }
        Long uploadType = Objects.isNull(type) ? UploadFileTypeEnum.APK.getLongCode() : type;
        SpUploadVO spUploadVO = new SpUploadVO();
        int i = APPVersionCheckUtil.strToInt(appId);
        spUploadVO.setAppId(new Long(i));
        spUploadVO.setFile(fileUpload);
        if (uploadType.equals(UploadFileTypeEnum.PICTURE.getLongCode())) {
            return spUploadService.uploadPictureFile(spUploadVO);
        }
        return spUploadService.uploadFile(spUploadVO);
    }

    @RequestMapping(value = "/download/{fileId}")
    @ApiOperation(value = "文件下载", notes = "文件下载")
    public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") String fileId) {
        return spUploadService.download(request, response, fileId);
    }

}

